<?php
/**
 * Created by PhpStorm.
 * User: peter
 * Date: 2018/6/21
 * Time: 下午7:30
 */

namespace app\mall\logic;


use app\model\Category;
use app\model\GoodsAttach;
use app\model\GoodsAttributeAttach;
use app\model\GoodsCollection;
use extend\Functions;
use extend\STATUS_CODE;
use Fukuball\Jieba\Finalseg;
use Fukuball\Jieba\Jieba;

class Goods
{
    /**
     * @purpose 获取随机商品
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function rand (): array
    {
        $model          = new \app\model\Goods();
        $result     = $model
            ->alias('g')
            ->join('goods_attach ga','g.id = ga.goods_id')
            ->orderRaw('rand()')
            ->field('g.id,g.title,g.thumb,g.price,ga.views')
            ->where('g.status', 99)
            ->page(1, 20)
            ->select();
        return Functions::result(
            STATUS_CODE::SUCCESS,
            $result
        );
    }
    /**
     * @purpose 通过商品ID获取相关商品
     * @param int $goods_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function relevantItemByGoodsId (int $goods_id):array
    {
        $model      = new \app\model\Goods();
        $goods_info = $model
            ->where('id', $goods_id)
            ->column('category,brand', 'id');
        $fields             = 'g.id,g.title,g.thumb,g.price,ga.views';
        $sort               = 'ga.views desc,ga.sales_volume desc,ga.collection desc,ga.shares desc,ga.comments desc';
        $result = $model
//            ->fetchSql(true)
            ->alias('g')
            ->join('goods_attach ga','g.id = ga.goods_id')
            ->where(
                'category=:category_id OR brand=:brand_id',
                [
                    'category_id' => $goods_info[$goods_id]['category'],
                    'brand_id' => $goods_info[$goods_id]['brand'],
                ])
            ->where([[
                ['g.id', '<>', $goods_id],
                ['g.status', '=', 99]
            ]])
            ->order($sort)
            ->field($fields)
            ->page(1, 20)
            ->select();
        return Functions::result(
            STATUS_CODE::SUCCESS,
            $result
        );
    }
    /**
     * @purpose 获取列表
     * @param int $page
     * @param int $size
     * @param $category_id
     * @param $brand_id
     * @param $sort
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function items (
        int $page = 1,
        int $size = 20,
        $category_id,
        $brand_id,
        $sort = 1):array
    {
        $where[]      = ['status', '=', 99];
        if ($brand_id) {
            $where[]    = ['brand', '=', $brand_id];
        }
        if ($category_id) {
            $category = new Category();
            $category_children_ids = $category->getChildrenIdByPid($category_id);
            $where[]    = ['category', 'in', $category_children_ids];
        }
        $_sort      = [
            1 => 'ga.views desc,ga.sales_volume desc,ga.collection desc,ga.shares desc,ga.comments desc',
            2 => 'ga.sales_volume desc,ga.views desc,ga.collection desc,ga.shares desc,ga.comments desc',
            3 => 'g.price desc,ga.views desc,ga.sales_volume desc,ga.collection desc,ga.shares desc,ga.comments desc'
        ];

        $fields = 'g.id,g.title,g.thumb,g.price,ga.views';
        $model  = new \app\model\Goods();
        $total  = $model->total($where);
        $result = $model
            ->alias('g')
            ->join('goods_attach ga','g.id = ga.goods_id')
            ->where($where)
            ->order($_sort[$sort])
            ->field($fields)
            ->page($page, $size)
            ->select();

        return Functions::result(
            STATUS_CODE::SUCCESS,
            [
                'total' => $total,
                'list'  => $result
            ]
        );
    }
    /**
     * @purpose 搜索商品 todo 暂时不使用搜索引擎
     * @param string $keywords
     * @param int $page
     * @param int $size
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function search (
        string $keywords,
        int $page = 1,
        int $size = 20):array
    {
        // 开始分词
        ini_set('memory_limit', '1024M');
        Jieba::init();
        Finalseg::init();
        $_keywords = [];
        if (mb_strlen($keywords, 'GBK') <= 10) {
            $_keywords = preg_split('/(?<!^)(?!$)/u', $keywords);
        }
        $__keywords = Jieba::cutForSearch($keywords);
//        $_keywords = Jieba::cut($keywords, true);
        if (!in_array($keywords, $_keywords)) {
            array_push($_keywords, $keywords);
        }
        $_keywords = array_unique(array_merge($_keywords, $__keywords));
//        foreach ($_keywords as $keyword) {
//            array_push($_keywords, Functions::pinyin($keyword));
//        }
        $model      = new \app\model\Goods();
        $where      = [];
        $where[]    = ['status', '=', 99];
        $_keyword   = [];
        foreach ($_keywords as $keyword) {
            array_push($_keyword, '%' . $keyword);
            array_push($_keyword, '%' . $keyword . '%');
            array_push($_keyword, $keyword . '%');
        }
        // 组装mysql权重查询
        $fields     = 'g.id,g.title,g.thumb,g.price,ga.views,';
        $fields     .= '(';
        foreach ($_keywords as $keyword) {
            $fields .= '((LENGTH(g.title) - LENGTH(REPLACE(g.title, "'. $keyword .'", ""))) / LENGTH("'.$keyword.'")) + ';
        }
        $fields     = rtrim($fields, '+ ');
        $fields     .= ') as title_count, (';
        foreach ($_keywords as $keyword) {
            $fields .= '(LENGTH(g.category_name) - LENGTH(REPLACE(g.category_name, "'. $keyword .'", "")) / LENGTH("'.$keyword.'")) + ';
        }
        $fields     = rtrim($fields, '+ ');
        $fields .= ') as category_count,(';
        foreach ($_keywords as $keyword) {
            $fields .= '(LENGTH(g.brand_name) - LENGTH(REPLACE(g.brand_name, "'. $keyword .'", "")) / LENGTH("'.$keyword.'")) + ';
        }
        $fields     = rtrim($fields, '+ ');
        $fields .= ') as brand_count';
        // 检索标题
        $where[]    = [
            'title|category_name|brand_name',
            'like',
            $_keyword,
            'or'];

        $total      = $model->total($where);
        $result     = $model
//            ->fetchSql(true)
            ->alias('g')
            ->join('goods_attach ga','g.id = ga.goods_id')
            ->where($where)
            ->order('title_count desc,category_count desc,brand_count desc,ga.views desc')
            ->field($fields)
            ->page($page,$size)
            ->select();
        return Functions::result(
            STATUS_CODE::SUCCESS,
            [
                'total' => $total,
                'list'  => $result
            ]
        );
    }

    /**
     * @purpose 获取商品详情
     * @param int $goods_id
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function detail (int $goods_id, $token):array
    {
        $model      = new \app\model\Goods();
        $attach     = new GoodsAttach();
        $result     = $model
            ->with('attach,attribute')
            ->where('id', $goods_id)
            ->where('status', 99)
            ->field('id,title,thumb,images,price,stock')
            ->find();
        $attach
            ->where('goods_id', $goods_id)
            ->setInc('views', 1);
        if ($result) {
            $result = $result->toArray();
            $result['is_collection'] = false;
        } else {
            return Functions::result(
                STATUS_CODE::FAIL,
                '商品不存在,或已下架!'
            );
        }
        if ($token) {
            $member = new \app\model\Member();
            $collection = new GoodsCollection();
            $uid    = $member
                ->where('token', $token)
                ->value('uid');
            $result['is_collection'] = (bool) $collection
                ->where('uid', $uid)
                ->where('goods_id', $goods_id)
                ->count();
        }
        return Functions::result(
            STATUS_CODE::SUCCESS,
            $result
        );
    }

    /**
     * @purpose 根据商品编号获取指定属性的商品信息
     * @param string $number
     * @param int $goods_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function attach (string $number, int $goods_id):array
    {
        $number = Functions::str_sort($number);
        $model     = new GoodsAttributeAttach();
        $result    = $model
            ->where('number', $number)
            ->where('goods_id', $goods_id)
            ->field('price,stock,thumb')
            ->find();
        return Functions::result(
            STATUS_CODE::SUCCESS,
            $result
        );
    }
}